
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class JmTest {
    public static void main(String[] args) {
        System.out.println("test start");
        String sign = HmacUtil.encodeSHA256("abc","123456");
        System.out.println(sign);
    }
}


 class HmacUtil {

    private HmacUtil() {
    }

    private static final String MAC_NAME_1 = "HmacSHA1";
    private static final String MAC_NAME_256 = "HmacSHA256";


    private static byte[] encode(String macName, String encryptKey, String encryptText) {
        try {
            byte[] data = encryptKey.getBytes(StandardCharsets.UTF_8);
            SecretKey secretKey = new SecretKeySpec(data, macName);
            Mac mac = Mac.getInstance(macName);
            mac.init(secretKey);

            byte[] text = encryptText.getBytes(StandardCharsets.UTF_8);
            return mac.doFinal(text);
        } catch (Exception e) {
//            log.error("HmacSHA1...", e);
        }
        return new byte[0];
    }


    public static String encodeSHA1(String encryptKey, String encryptText) {
        byte[] data = encode(MAC_NAME_1, encryptKey, encryptText);
        return HexUtils.toHexString(data);
    }

    public static String encodeSHA256(String encryptKey, String encryptText) {
        byte[] data = encode(MAC_NAME_256, encryptKey, encryptText);
        return HexUtils.toHexString(data);
    }

}


/**
 */
 class HexUtils {

    private HexUtils() {
    }


    public static byte[] toHex(byte[] digestByte) {
        byte[] rtChar = new byte[digestByte.length * 2];
        for (int i = 0; i < digestByte.length; i++) {
            byte b1 = (byte) (digestByte[i] >> 4 & 0x0f);
            byte b2 = (byte) (digestByte[i] & 0x0f);
            rtChar[i * 2] = (byte) (b1 < 10 ? b1 + 48 : b1 + 55);
            rtChar[i * 2 + 1] = (byte) (b2 < 10 ? b2 + 48 : b2 + 55);
        }
        return rtChar;
    }

    public static String toHexString(byte[] digestByte) {
        return new String(toHex(digestByte));
    }

    public static byte[] fromHex(byte[] sc) {
        byte[] res = new byte[sc.length / 2];
        for (int i = 0; i < sc.length; i++) {
            byte c1 = (byte) (sc[i] - 48 < 17 ? sc[i] - 48 : sc[i] - 55);
            i++;
            byte c2 = (byte) (sc[i] - 48 < 17 ? sc[i] - 48 : sc[i] - 55);
            res[i / 2] = (byte) (c1 * 16 + c2);
        }
        return res;
    }

    public static byte[] fromHexString(String hex) {
        return fromHex(hex.getBytes());
    }

    /**
     *
     * @param in
     * @return
     */
    public static String encode(String in) {
        return new String(toHex(in.getBytes()));
    }

    /**
     *
     * @param in
     * @return
     */
    public static String decode(String in) {
        return new String(fromHex(in.getBytes()));
    }

}